package com.zy.servlet;

import com.zy.entity.User;
import com.zy.service.impl.LoginServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private LoginServiceImpl serviceImpl = new LoginServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理用户登录的请求
        String username = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = serviceImpl.login(username, password);

        if (user != null) {
            // 根据用户类型重定向到不同的页面
            if (user.getUserType() == 0) {
                resp.sendRedirect("admin.jsp");
            } else {
                resp.sendRedirect("index.jsp");
            }
            req.getSession().setAttribute("loggedIn", true);
            req.getSession().setAttribute("userId", user.getId());
            req.getSession().setAttribute("username", user.getUserName());
        } else {
            // 登录失败，重定向到错误页面
            resp.sendRedirect("error.jsp");
        }
    }
} 